<?php

namespace app\middlewares;

use Slim;
use slimExt\base\Request;
use slimExt\base\Response;
use inhere\librarys\env\Server;
use inhere\librarys\env\Client;

/**
 * Class BeforeLogic
 * @package slimExt\middlewares
 */
class BeforeLogic
{

    /**
     * Auth middleware invokable class
     *
     * @param  Request   $req  PSR7 request
     * @param  Response  $res PSR7 response
     * @param  callable  $next     Next middleware
     *
     * @return Response
     */
    public function __invoke(Request $req, Response $res, $next)
    {
        $client = Client::make();

        $collect = [
            Server::value('request_time'),
            $client->ip,
            $client->method,
            $client->uri,
            $client->getHeader('referer', '--'),
            $client->os,
            $client->browser,
        ];

        // Sample log message
        Slim::$app->logger->info( implode(' ', $collect) . ' ', $req->getParams());

        // set css theme by cookie
        if ( !empty($req->getCookieParams()['css_style']) ) {
            $cssStyle = $req->getCookieParams()['css_style'];
            $cssFile = Slim::alias('@assets/libs/bootswatch') . "/$cssStyle/bootstrap.min.css";

            if ($cssStyle !== Slim::config()->get('params.cssStyle') && file_exists($cssFile) ) {
                Slim::config()->set('params.cssStyle', $cssStyle);
            }
        }

        return $next($req, $res);
    }
}